package com.example.demo.common;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.*;

/**
 * 全局的的异常处理器
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler({MethodArgumentNotValidException.class})
    public Map<String, Object> bodyValidExceptionHandler(MethodArgumentNotValidException e) {
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("code", -1);

        List<FieldError> fieldErrors = Optional.ofNullable(e).map(MethodArgumentNotValidException::getBindingResult).map(BindingResult::getFieldErrors).orElse(new ArrayList<>());
        log.error("参数绑定异常,ex = {}", JSON.toJSONString(fieldErrors));
        if (CollectionUtils.isEmpty(fieldErrors)) {
            resultMap.put("message", "未知异常!");
            return resultMap;
        }

        StringBuilder sb = new StringBuilder();
        for (FieldError error : fieldErrors) {
            sb.append(error.getField()).append(" ").append(error.getDefaultMessage());
            break;
        }

        resultMap.put("message", sb.toString());
        return resultMap;
    }
}
